package com.example.jussi.alipaydemo;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.example.jussi.alipatstander.AlipayInterface;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ProxyActivity extends AppCompatActivity {
    public String entryActivityName;    //要跳转的（淘票票）Activity
    private String className;
    AlipayInterface alipayInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_proxy);
        className = getIntent().getStringExtra("className");

        /*Class clazz = getClassLoader().loadClass(className);
        Class.forName(className)
        这种方法得到的是本活动（支付宝）的 Class
        而我们需要的是另一个活动的 Class */
        try {
            /**
             * 定义标准
             * 传递生命周期
             */
            Class activityClass = getClassLoader().loadClass(className);    //拿到其他活动（淘票票）的类加载器
            Constructor constructor = activityClass.getConstructor(new Class[]{});  //拿到其他活动（淘票票）的构造器
            Object instance = constructor.newInstance(new Object[]{});  //实例化一个淘票票
            alipayInterface = (AlipayInterface) instance;
            alipayInterface.attach(this);   //通过 alipayInterface 传递本活动（支付宝）的生命周期
            Bundle bundle = new Bundle();
            alipayInterface.onCreate(bundle);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        alipayInterface.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        alipayInterface.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        alipayInterface.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        alipayInterface.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        alipayInterface.onDestroy();
    }

    /**
     * 重写达到加载 非本活动（淘票票） 的 Class
     * @return
     */
    @Override
    public ClassLoader getClassLoader() {
        return PluginManager.getInstance().getDexClassLoader();
    }

    @Override
    public Resources getResources() {
        return PluginManager.getInstance().getResources();
    }
}
